# zbx_itemctl/zbx_itemctl/cli.py
import os
import typer
from dotenv import load_dotenv
from .client import ZabbixClient
from .item_service import ItemService

app = typer.Typer()

load_dotenv(".env")

URL = os.getenv("ZABBIX_URL", "http://150.158.45.251:8080/api_jsonrpc.php")
USER = os.getenv("ZABBIX_USER", "Admin")
PWD = os.getenv("ZABBIX_PWD", "zabbix")

def get_service() -> ItemService:
    client = ZabbixClient(URL, USER, PWD)
    return ItemService(client)

@app.command("list")
def list_items(
    hostid: str = typer.Option(None, help="过滤指定 hostid"),
    key: str = typer.Option(None, help="模糊匹配 key_"),
):
    svc = get_service()
    items = svc.list_items(hostid=hostid, key_=key)
    for it in items:
        typer.echo(f"{it['itemid']} | {it['name']} | {it['key_']}")

@app.command("create")
def create_item(
    hostid: str = typer.Argument(..., help="主机 ID"),
    name: str = typer.Argument(..., help="监控项名称"),
    key: str = typer.Argument(..., help="监控项 key"),
    delay: str = typer.Option("30s", help="刷新间隔"),
):
    svc = get_service()
    itemid = svc.create_item(hostid=hostid, name=name, key_=key, delay=delay)
    typer.echo(f"已创建 itemid={itemid}")

@app.command("list-hosts")
def list_hosts():
    svc = get_service()
    hosts = svc.list_hosts()
    # 打印表头
    typer.echo(f"{'主机ID':<10} | {'主机名':<20} | {'可见名':<20}")
    typer.echo("-" * 54)
    for host in hosts:
        typer.echo(f"{host['hostid']:<10} | {host['host']:<20} | {host['name']:<20}")

if __name__ == "__main__":
    app()